package main

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"

	"encoding/hex"
	"hash"
	"io/ioutil"
	"os"
)

type hashHandler func([]byte) []byte
var hashes = map[string]hashHandler{
	"md5": getHashHandler(md5.New),
	"sha1": getHashHandler(sha1.New),
	"sha256": getHashHandler(sha256.New),
	"sha512": getHashHandler(sha512.New),
}

func getHashHandler(getHash func() hash.Hash) hashHandler {
	return func(b []byte) (o []byte) {
		h := getHash()
		_, e := h.Write(b)
		if e != nil {
			// According to the package spec, this should never
			// happen. Do we trust the package spec? ...Not today.
			panic(e)
		}
		o = h.Sum(o)
		return o
	}
}

func hashCmd(n string) {
	hh, ok := hashes[n]
	if !ok {
		os.Stderr.WriteString("crypto: "+n+": no such hash\n")
		os.Exit(1)
	}
	buf, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		os.Stderr.WriteString(n + ": " + err.Error())
	}
	println(hex.EncodeToString(hh(buf)))
}
